package com.terren.spider.util.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.log4j.Logger;

public class RandomCookie {
	private static Logger logger = Logger.getLogger(RandomUA.class.getName());
	private static ArrayList<String> cookieList = new ArrayList<String>();
	private static boolean loadCookie = false;

	public static String getRandomWbCookie() {
		if(!loadCookie)
			cookieList = importWbCookie();
		int n = (int)Math.floor(Math.random() * cookieList.size());
		int i = 0;
		String randomCookie = "";
		for(String cookie : cookieList) {
			if(i == n) {
				randomCookie = cookie;
				break;
			}
			i++;
		}
		logger.info("Fetch a cookie that " + getUN(randomCookie));
		return randomCookie;
	}

	private static String getUN(String cookie) {
		return cookie.substring(cookie.indexOf("un="));
	}
	
	private static ArrayList<String> importWbCookie(){
		ArrayList<String> cookieLs = new ArrayList<String>();
		try{
			File file = new File("./Data/wbcookie.txt");
	    	InputStreamReader fr = new InputStreamReader( new FileInputStream(file),"GBK"); 
			BufferedReader br = new BufferedReader(fr);
			String str = br.readLine();
			while(str != null && str.length() > 0) {
				cookieLs.add(str);
				str = br.readLine();
			}
			br.close();
			fr.close();
			loadCookie = true;
			logger.info("Reading " + cookieLs.size() + " Weibo cookies.");
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return cookieLs;
	}
}
